/******************************************************************************
 * Copyright (C) 2011 ShenZhen ComTop Information Technology Co.,Ltd
 * All Rights Reserved.
 * 本软件为深圳康拓普开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、
 * 复制、修改或发布本软件.
 *****************************************************************************/

package com.code.common.logback;

import javax.servlet.ServletContext;

import org.springframework.beans.BeansException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.code.common.commonpool.ObjectPool;
import com.code.common.nosql.MongoDBService;
import com.code.common.systeminit.EnviromentInfo;

/**
 * @author 周振兴
 * @since 1.0
 * @version 2011-2-28 周振兴
 */
public class MongoDBAppender extends AbstractBsonAppender {
    
    /** 是否实例化 */
    private boolean initialized;
    
    /**
     * 服务对象
     */
    private static MongoDBService mongoDBService;
    
    /**
     * 池对象
     */
    private static ObjectPool fooService;
    
    @Override
    public void start() {
        super.start();
        init();
    }
    
    /**
     * 初始化服务
     */
    private void init() {
        try {
            ServletContext objServletContext = EnviromentInfo.getServletContext();
            if (objServletContext != null) {
                // WebApplicationContext webApplicationContext = EnviromentInfo.getWebApplicationContext();
                WebApplicationContext objWebApplicationContext =
                    WebApplicationContextUtils.getWebApplicationContext(objServletContext);
                if (objWebApplicationContext != null) {
                    fooService = objWebApplicationContext.getBean("mongoDBPool", ObjectPool.class);
                }
            }
        } catch (BeansException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void append(LoggingEventVO loggingEventVO) {
        if (fooService == null) {
            init();
            if (fooService == null) {
                return;
            }
        }
        if (initialized && loggingEventVO != null) {
            try {
                mongoDBService = (MongoDBService) fooService.borrowObject();
                //mongoDBService.save("log", loggingEventVO);
                fooService.returnObject(mongoDBService);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * @return 获取 initialized属性值
     */
    public boolean isInitialized() {
        return initialized;
    }
    
    /**
     * @param initialized 设置 initialized 属性值为参数值 initialized
     */
    public void setInitialized(boolean initialized) {
        this.initialized = initialized;
    }
}